package com.treasure.mall.zbqmallmanager.controller.product;

import com.treasure.mall.biz.dto.condition.SpecialAreaCondition;
import com.treasure.mall.biz.entity.product.SpecialAreaProductPO;
import com.treasure.mall.biz.service.core.product.SpecialAreaService;
import com.treasure.mall.zbq.common.base.ApiResult;
import com.treasure.mall.zbq.common.constant.Constant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

/**
 * @author allan
 * @version 1.0.0
 * @date 2020/6/22
 */
@Controller
@RequestMapping("/specialArea")
public class SpecialAreaController {
    @Autowired
    private SpecialAreaService specialAreaService;

    @GetMapping("/list")
    public String areaList(Model model) {
        model.addAttribute("areas", specialAreaService.areaList());

        return "product/special_area_list";
    }

    @GetMapping("/products")
    public String areaProducts(
            @ModelAttribute("condition") SpecialAreaCondition condition,
            @RequestParam(required = false, defaultValue = "1") int pageIndex,
            Model model
    ) {
        Page<SpecialAreaProductPO> productPOS = specialAreaService.findAll(pageIndex, Constant.DEFAULT_PAGE_SIZE, condition);

        model.addAttribute("pageIndex", pageIndex);
        model.addAttribute("totalRecords", productPOS.getTotalElements());
        model.addAttribute("totalPages", productPOS.getTotalPages());
        model.addAttribute("products", productPOS.getContent());
        model.addAttribute("area", specialAreaService.findAreaById(condition.getAreaId()));

        return "product/special_area_products";
    }

    @PostMapping("/products/add")
    @ResponseBody
    public ApiResult addProduct(String[] areaId, Long productId) {
        specialAreaService.addProduct(productId, areaId);

        return ApiResult.ok();
    }

    @PostMapping("/products/changeOrder")
    @ResponseBody
    public ApiResult changeOrder(Long id, int orderWeight) {
        SpecialAreaProductPO productPO = specialAreaService.findById(id);
        productPO.setOrderWeight(orderWeight);
        specialAreaService.save(productPO);

        return ApiResult.ok();
    }

    @PostMapping("/products/remove")
    @ResponseBody
    public ApiResult removeProduct(Long id) {
        specialAreaService.removeProduct(id);

        return ApiResult.ok();
    }

    @PostMapping("/edit")
    @ResponseBody
    public ApiResult editArea(String areaId, String title, String desc) {
        specialAreaService.editArea(areaId, title, desc);

        return ApiResult.ok();
    }
}
